const cloud = require('@cloudbase/node-sdk')

// 初始化云开发实例
const app = cloud.init({
    env: cloud.SYMBOL_CURRENT_ENV
})

// 获取数据库引用
const db = app.database()
const collection = db.collection('skills_list')

/**
 * skills_list CRUD 云函数
 * @param {Object} event - 云函数参数
 * @param {Object} context - 云函数上下文
 */
exports.main = async (event, context) => {
    const { action, data } = event

    try {
        // 操作日志
        console.log('skills-list-crud 调用:', { action, data })

        switch (action) {
            case 'create':
                return await createSkill(data)
            case 'read':
                return await getSkill(data)
            case 'update':
                return await updateSkill(data)
            case 'delete':
                return await deleteSkill(data)
            case 'list':
                return await listSkills(data)
            default:
                throw new Error('无效的操作类型')
        }
    } catch (error) {
        console.error('skills-list-crud 错误:', error)
        return {
            code: -1,
            message: error.message,
            data: null
        }
    }
}

// 创建技能项
async function createSkill(data) {
    const { content, date, likes, summary, tag, title, views, enable } = data

    if (!title || !content || !summary) {
        throw new Error('标题、内容和摘要为必填项')
    }

    const skillData = {
        content,
        date,
        likes: likes || '0',
        summary,
        tag,
        title,
        views: views || '0',
        enable: enable !== false,
        id: `skill_${Date.now()}`, // 生成唯一ID
        createdAt: new Date(),
        updatedAt: new Date()
    }

    const result = await collection.add(skillData)

    return {
        code: 0,
        message: '创建成功',
        data: result
    }
}

// 获取单个技能项
async function getSkill(data) {
    const { _id } = data

    if (!_id) {
        throw new Error('_id为必填项')
    }

    const result = await collection.doc(_id).get()

    if (!result.data || result.data.length === 0) {
        throw new Error('技能项不存在')
    }

    return {
        code: 0,
        message: '查询成功',
        data: result.data[0]
    }
}

// 更新技能项
async function updateSkill(data) {
    const { _id, content, date, likes, summary, tag, title, views, enable } = data

    if (!_id) {
        throw new Error('_id为必填项')
    }

    const updateData = {
        updatedAt: new Date()
    }

    if (content !== undefined) updateData.content = content
    if (date !== undefined) updateData.date = date
    if (likes !== undefined) updateData.likes = likes
    if (summary !== undefined) updateData.summary = summary
    if (tag !== undefined) updateData.tag = tag
    if (title !== undefined) updateData.title = title
    if (views !== undefined) updateData.views = views
    if (enable !== undefined) updateData.enable = enable

    const result = await collection.doc(_id).update(updateData)

    return {
        code: 0,
        message: '更新成功',
        data: result
    }
}

// 删除技能项
async function deleteSkill(data) {
    const { _id } = data

    if (!_id) {
        throw new Error('_id为必填项')
    }

    const result = await collection.doc(_id).remove()

    return {
        code: 0,
        message: '删除成功',
        data: result
    }
}

// 获取技能项列表
async function listSkills(data) {
    const { page = 1, pageSize = 10, title, tag, content, summary, enableStatus } = data

    // 构建查询条件
    let queryConditions = {}

    // 添加查询条件
    if (title) {
        queryConditions.title = db.RegExp({
            regexp: title,
            options: 'i'
        })
    }

    if (tag) {
        queryConditions.tag = db.RegExp({
            regexp: tag,
            options: 'i'
        })
    }

    if (content) {
        queryConditions.content = db.RegExp({
            regexp: content,
            options: 'i'
        })
    }

    if (summary) {
        queryConditions.summary = db.RegExp({
            regexp: summary,
            options: 'i'
        })
    }

    // 处理启用状态筛选
    if (enableStatus !== undefined) {
        if (enableStatus === 'enabled') {
            // 启用状态：enable 为 true 或不存在
            queryConditions = db.command.or([
                { enable: true },
                { enable: db.command.exists(false) }
            ])
        } else if (enableStatus === 'disabled') {
            // 禁用状态：enable 为 false
            queryConditions.enable = false
        }
    }

    const query = collection.where(queryConditions)

    const result = await query
        .orderBy('updatedAt', 'desc')
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .get()

    const countResult = await query.count()

    return {
        code: 0,
        message: '查询成功',
        data: {
            list: result.data,
            total: countResult.total,
            page,
            pageSize
        }
    }
}